//
//  HSYBaseVideoPlayerView+PanGestrues.m
//  高仿暴走斗图
//
//  Created by key on 16/8/17.
//  Copyright © 2016年 huangsongyao. All rights reserved.
//

#import "HSYBaseVideoPlayerView+PanGestrues.h"
#import <AVFoundation/AVFoundation.h>

#define SYSTEM_BRIGHTNESS_BASE_VALUE            10000.0f                //亮度的分母
#define SYSTEM_VOLUME_BASE_VALUE                10000.0f                //声音的分母

#define VIDEO_CHANGE_BASE_VALUE                 200.0f                  //滑动手势下的进度比例
#define MIN_SUM_VALUE                           0.0f                    //最小值

#define SYSTEM_VOLUME_VIEW_FRAME                CGRectMake(-SYSTEM_BRIGHTNESS_BASE_VALUE, -SYSTEM_VOLUME_BASE_VALUE, 0, 0);
#define MP_VOLUME_SLIDER                        @"MPVolumeSlider"

static MPVolumeView *volumeView = nil;

@implementation HSYBaseVideoPlayerView (PanGestrues)

+ (MPVolumeView *)shareVolumeInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        volumeView = [[MPVolumeView alloc] init];
        volumeView.frame = SYSTEM_VOLUME_VIEW_FRAME;
        volumeView.hidden = NO;
    });
    return volumeView;
}

- (UISlider *)volumeViewSlider
{
    MPVolumeView *volumeView = [HSYBaseVideoPlayerView shareVolumeInstance];
    UISlider *volumeViewSlider = nil;
    for (UIView *view in [volumeView subviews]) {
        if ([view.class.description isEqualToString:MP_VOLUME_SLIDER]) {
            volumeViewSlider = (UISlider *)view;
            break;
        }
    }
    //设置不跟随手机静音键打开而静音，可在手机静音下播放声音
    NSError *error = nil;
    BOOL success = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
    NSLog(@"success : %d", success);

    return volumeViewSlider;
}

//*****************************************************************************************************************************************************//

- (void)handlePanGesture:(UIPanGestureRecognizer *)gesture
{
    CGPoint locationPoint = [gesture locationInView:self.clearMask];
    CGPoint veloctyPoint = [gesture velocityInView:self.clearMask];
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan: {                                               //开始移动
            CGFloat x = fabs(veloctyPoint.x);
            CGFloat y = fabs(veloctyPoint.y);                                               //使用绝对值来判断移动的方向
            if (x > y) {                                                                    //水平移动
                self.panDirection = kPanGestureDirectionTypeHorizontalMoved;
                self.sumTime = self.value;                                                  //sumTime初值
                NSLog(@"sumTime :%f", self.sumTime);
                //暂停播放
                if (self.delegate && [self.delegate respondsToSelector:@selector(progessControlEventTouchBeganForSlider:)]) {
                    [self.delegate progessControlEventTouchBeganForSlider:self.volumeViewSlider];
                }
            } else if (x < y) {                                                             //垂直移动
                self.panDirection = kPanGestureDirectionTypeVerticalMoved;
                
                if (locationPoint.x > self.viewWidth / 2) {                                 //开始滑动的时候,状态改为正在控制音量
                    self.isVolume = YES;                                                    //状态为调节设备音量
                } else {
                    self.isVolume = NO;                                                     //状态改为显示亮度调节
                }
            }
            break;
        }
        case UIGestureRecognizerStateChanged: {                                             //正在移动
            switch (self.panDirection) {
                case kPanGestureDirectionTypeHorizontalMoved: {
                    [self horizontalMoved:veloctyPoint.x];                                  //水平移动的方法只要x方向的值
                }
                    break;
                    
                case kPanGestureDirectionTypeVerticalMoved: {
                    [self verticalMoved:veloctyPoint.y];                                    //垂直移动方法只要y方向的值
                }
                    break;
                default:
                    break;
            }
            break;
        }
        case UIGestureRecognizerStateCancelled:
        case UIGestureRecognizerStateEnded: {                                               //移动停止
            switch (self.panDirection) {
                case kPanGestureDirectionTypeHorizontalMoved: {
                    //继续播放
                    if (self.delegate && [self.delegate respondsToSelector:@selector(progessControlEventTouchEndedForValue:)] && self.maxValue > MIN_SUM_VALUE) {
                        [self.delegate progessControlEventTouchEndedForValue:@(self.sumTime)];
                    }
                }
                    break;
                    
                case kPanGestureDirectionTypeVerticalMoved: {
                    self.isVolume = NO;                                                     //垂直移动结束后，把状态改为不再控制音量
                }
                    break;
                default:
                    break;
            }
            break;
        }
        default:
            break;
    }
}

- (void)verticalMoved:(CGFloat)value
{
    self.isVolume ? (self.volumeViewSlider.value -= value / SYSTEM_VOLUME_BASE_VALUE) : ([UIScreen mainScreen].brightness -= value / SYSTEM_BRIGHTNESS_BASE_VALUE);
}

- (void)horizontalMoved:(CGFloat)value
{
    if (self.maxValue <= MIN_SUM_VALUE) {
        return;
    }
    // 快进快退的方法
    self.sumTime += value / VIDEO_CHANGE_BASE_VALUE;
    if (self.sumTime > self.maxValue) {
        self.sumTime = self.maxValue;
    } else if (self.sumTime < MIN_SUM_VALUE) {
        self.sumTime = MIN_SUM_VALUE;
    }
    // 时间更新
    double currentTime = self.sumTime;
    double totalTime = self.maxValue;
    @weakify(self);
    dispatch_async(dispatch_get_main_queue(), ^{
        @strongify(self);
        self.timeIndicatorView.indicatorTime = [self setTimeLabelValues:currentTime totalTime:totalTime];
        kTimeIndicatorPlayStateType playState = kTimeIndicatorPlayStateTypeRewind;
        if (value < MIN_SUM_VALUE) {
            playState = kTimeIndicatorPlayStateTypeRewind;
        } else if (value > MIN_SUM_VALUE) {
            playState = kTimeIndicatorPlayStateTypeFastForward;
        }
        if (self.timeIndicatorView.indiccatorType != playState) {
            if (value < MIN_SUM_VALUE) { // left
                self.timeIndicatorView.indiccatorType = kTimeIndicatorPlayStateTypeRewind;
                [self.timeIndicatorView setNeedsLayout];
            } else if (value > MIN_SUM_VALUE) { // right
                self.timeIndicatorView.indiccatorType = kTimeIndicatorPlayStateTypeFastForward;
                [self.timeIndicatorView setNeedsLayout];
            }
        }
        if (self.didPanGestrueChangeValueBlock) {
            self.didPanGestrueChangeValueBlock(@(currentTime));
        }
    });
}


@end
